package com.itsu.spbspider.service.impl;

import com.alibaba.fastjson.JSON;
import com.itsu.spbspider.entity.source.ParamsWeather;
import com.itsu.spbspider.mapper.CrawlerMapper;
import com.itsu.spbspider.service.Crawler;
import com.itsu.spbspider.util.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author suben
 * @create time 2020/2/12 18:09
 */
@Service("baiduWeatherAreaCrawler")
public class BaiduWeatherAreaCrawler implements Crawler {

    @Resource
    CrawlerMapper crawlerMapper;

    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String crawlerData(Integer crawlId) throws Exception {
        com.itsu.spbspider.entity.Crawler crawler = crawlerMapper.selectById(crawlId);
        Map<String, String> headers = initHeadersParams(crawler.getHeaders(), "headers");
        Map<String, String> params = initHeadersParams(crawler.getParams(), "params");
        String content = null;
        if ("GET".equals(crawler.getMethod().toUpperCase())) {
            content = HttpUtil.get(crawler.getUrl(), params, headers);
        } else {
            content = HttpUtil.post(crawler.getUrl(), params, headers);
        }
        return content;
    }

    public Map<String, String> initHeadersParams(String content, String type) throws IllegalAccessException {
        Map<String, String> ret = new HashMap<>();
        if (StringUtils.isBlank(content)) {
            return ret;
        }
        ParamsWeather paramsWeather = JSON.parseObject(content).toJavaObject(ParamsWeather.class);
        Field[] fields = paramsWeather.getClass().getDeclaredFields();
        List<Field> fieldList = Arrays.stream(fields).filter(x -> {
            try {
                x.setAccessible(true);
                if (x.get(paramsWeather) != null) {
                    return true;
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return false;
        }).collect(Collectors.toList());

        for (Field field : fieldList) {
            ret.put(field.getName(), field.get(paramsWeather).toString());
        }
        if (StringUtils.equals("params", type)) {
            ret.put("id", this.id);
        }
        return ret;
    }
}
